<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import axios from 'axios'
import { showNotify } from 'vant';
import { useRouter } from 'vue-router'
import { setBg, bgColors, isPhone, uploadFile, isNotEmpty, getDeviceType } from '@/plugins/util.js'
import { setUserExtInfoApi } from '@/plugins/http/api/user'
import { getImgsApi } from '@/plugins/http/api/common'


import { useUser } from '@/composition/useUser'

const { user, loggedIn } = useUser();

const router = useRouter()
console.log(router.currentRoute.value)

const imgs = ref([])


onMounted(() => {
  if (isPhone()) {
    page.value.pageSize = 9;
  }
  let deviceType = getDeviceType();
  let bgInfo = user.value.extInfo.bg[deviceType];
  const bgUrl = bgInfo.url;
  if (isNotEmpty(bgUrl)) {
    fileList.value = [];
    fileList.value.push(
      {
        url: bgUrl,
        isImage: true
      }
    );
  }

})


const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const page = ref({
  pageNo: 1,
  pageSize: 10
});


const onLoad = () => {
  if (refreshing.value) {
    // 下拉刷新操作
    imgs.value = [];
    refreshing.value = false;
    page.value.pageNo = 1;
  }
  const imgType = getDeviceType();
  const pageNo = page.value.pageNo;
  const pageSize = page.value.pageSize;
  let urlType;
  if (activeTab.value == '图片') {
    urlType = 'getImgs';
  } else {
    urlType = 'getByImgs';
  }
  getImgsApi(urlType, imgType, pageNo, pageSize).then(imgApiRes => {
    if (imgApiRes.code == '0') {
      let imgList = imgApiRes.data.list || []

      // 数据填充
      imgs.value = imgs.value.concat(imgList)

      // 设置下一次查询的页码
      page.value.pageNo += 1;

      // 加载状态结束
      loading.value = false;

      // 数据全部加载完成
      if (imgList.length == 0) {
        finished.value = true;
      }
    } else {
      showNotify({ type: 'danger', message: '查询失败:' + response.data.message });
    }
  })
};


const onRefresh = () => {
  // 清空列表数据
  finished.value = false;
  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true;
  onLoad();
};

const imgClick = (img) => {
  // console.log(img)
  // console.log(img.imgName)
  // user.value.changeNum += 1;
  // debugger;
  // let user = JSON.parse(JSON.stringify(store.state.user.info));
  // user.changeNum += 1;
  // let bgInfo = user.extInfo.bg[deviceType];
  // bgInfo.url = img.imgUrl
  // bgInfo.color = ''
  // bgInfo.showType = 'url'
  // store.commit('user/setUser', user);
  setBgUrl(img.imgUrl)
}


const setBgUrl = (bgUrl) => {
  let deviceType = getDeviceType();
  let bgInfo = user.value.extInfo.bg[deviceType];
  bgInfo.url = bgUrl
  bgInfo.showType = 'url'
  setBg();
  if (loggedIn.value) {
    // save data to db
    let setUserExtInfoData = {
      appCode: 'F0FB4BED6B664CFEBBB30A688A4C8E3F',
      param: {
        userSet: user.value.extInfo
      }
    };
    setUserExtInfoApi(setUserExtInfoData).then(setUserExtInfoDataRes => {
      if (setUserExtInfoDataRes.code != '0') {
        showNotify({ type: 'danger', message: setUserExtInfoDataRes.message });
        return;
      }
      // showToast('保存设置成功');
      showNotify({ type: 'success', message: '保存设置成功' });
    })
  } else {
    showNotify({ type: 'success', message: '保存设置成功' });
  }
}


// none:无背景 url:链接 color:颜色
const tabs = ref([
  {
    showType: 'url',
    tabName: '图片'
  },
  {
    showType: 'url',
    tabName: '必应每日壁纸'
  },
  {
    showType: 'color',
    tabName: '颜色'
  },
  {
    showType: 'custom',
    tabName: '自定义'
  },

])

const activeTab = ref(tabs.value[0].tabName);


watch(activeTab, (newVal, oldVal) => {
  // console.log("newVal", newVal);
  // if (loading.value) {
  //   showNotify({ type: 'warning', message: '正在加载中，请稍等' });
  //   activeTab.value = oldVal;
  //   return;
  // }
  if (newVal == '图片') {
    refreshing.value = true;
    onRefresh();
  } else if (newVal == '必应每日壁纸') {
    refreshing.value = true;
    onRefresh();
  } else if (newVal == '颜色') {

  }
});


const colorClick = (color) => {
  // console.log(color)
  // console.log(color.color)
  // user.value.changeNum += 1;
  let deviceType = getDeviceType();
  const bg = user.value.extInfo.bg[deviceType];
  bg.color = color.color
  bg.showType = 'color'
  showNotify({ type: 'success', message: '设置成功' });
}


const fileList = ref([
  // {
  //   url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg',
  //   isImage: true
  // }
]);

const delImg = () => {
  setBgUrl('')
}

const afterRead = async (file, detail) => {
  let bgUrl;
  if (loggedIn.value) {
    const fileUrl = await uploadFile(file.file);
    bgUrl = fileUrl;
  } else {
    // base64
    bgUrl = file.content;
  }
  setBgUrl(bgUrl)
}


</script>

<template>
  <van-tabs v-model:active="activeTab" swipeable>

    <van-tab v-for="(tab, index) in tabs" :index="index" :title="tab.tabName" :name="tab.tabName" :disabled="loading">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh" v-show="activeTab == '图片' || activeTab == '必应每日壁纸'">
        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
          <!-- <van-cell v-for="item in list" :key="item" :title="item" /> -->
          <van-grid :border="false" :column-num="isPhone() ? 3 : 5" :clickable="true">
            <van-grid-item v-for="(img, idx) in imgs" :index="idx" :title="img.imgName" @click="imgClick(img)">
              <van-image :src='img.imgUrl' v-lazy="img" block fit="cover" position="top" />
            </van-grid-item>
          </van-grid>
        </van-list>
      </van-pull-refresh>

      <van-grid :border="false" :column-num="isPhone() ? 2 : 4" :clickable="true" v-show="activeTab == '颜色'">
        <van-grid-item v-for="(color, idx) in bgColors" :index="idx" :title="color.name" @click="colorClick(color)"
          :style="{ backgroundColor: color.color }">
          <div style="height: 150px;"></div>
        </van-grid-item>
      </van-grid>

      <div v-show="activeTab == '自定义'">
        <van-form>
          <van-cell-group inset>
            <van-field name="uploader" label="上传图片">
              <template #input>
                <van-uploader v-model="fileList" :after-read="afterRead" reupload max-count="1" @delete="delImg" />
              </template>
            </van-field>
          </van-cell-group>
        </van-form>
      </div>

      <!-- <van-row v-show="activeTab == '自定义'" align="center">
        <van-col span="4">上传图片</van-col>
        <van-col span="20">
          <van-uploader v-model="fileList" :after-read="afterRead" reupload max-count="1" @delete="delImg" />
        </van-col>
      </van-row> -->


    </van-tab>
  </van-tabs>

  <van-back-top />



  <!-- <van-grid :border="false" :column-num="3">
    <van-grid-item v-for="(img, idx) in imgs" :index="idx">
      <van-image :src=img.imgUrl />
    </van-grid-item>
  </van-grid> -->
</template>

<style scoped>
.login {
  display: grid;
  max-width: 600px;
  margin: 60px auto;
}

.van-grid-item {
  cursor: pointer;
}

:deep(.van-cell-group--inset) {
  margin: 0;
  border-radius: 0;
}

:deep(.van-cell-group) {
  background: rgb(255, 255, 255, 0.5);
  ;
}


:deep(.van-cell) {
  background: transparent;
}
</style>
